<?php


namespace app\admin\controller;


use app\common\controller\Backend;
use app\common\exception\UploadException;
use app\common\library\Upload;
use PhpOffice\PhpWord\Element\Image;
use PhpOffice\PhpWord\Element\Text;
use PhpOffice\PhpWord\Element\TextRun;
use PhpOffice\PhpWord\IOFactory;

class Article extends Backend
{
    /**
     * Ads模型对象
     * @var \app\admin\model\Article
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\Article();

    }

    public function import()
    {
        $file = $this->request->request('file');
        if (!$file) {
            $this->error(__('Parameter %s can not be empty', 'file'));
        }
        $filePath = ROOT_PATH . DS . 'public' . DS . $file;
        if (!is_file($filePath)) {
            $this->error(__('No results were found'));
        }
        $pathInfo = pathinfo($filePath);
        switch ($pathInfo['extension']) {
            case 'docx':
                // todo 导入的docx中处理包含的图片，判断oss上传还是本地上传
//                $phpWord = IOFactory::load($filePath);
//                $html = '';
//                foreach ($phpWord->getSections() as $section) {
//                    foreach ($section->getElements() as $ele1) {
//                        $paragraphStyle = $ele1->getParagraphStyle();
//                        if ($paragraphStyle) {
//                            $html .= '<p style="text-align:' . $paragraphStyle->getAlignment() . ';text-indent:20px;">';
//                        } else {
//                            $html .= '<p>';
//                        }
//                        if ($ele1 instanceof TextRun) {
//                            foreach ($ele1->getElements() as $ele2) {
//                                if ($ele2 instanceof Text) {
//                                    $style = $ele2->getFontStyle();
//                                    $fontFamily = mb_convert_encoding($style->getName(), 'GBK', 'UTF-8');
//                                    $fontSize = $style->getSize();
//                                    $isBold = $style->isBold();
//                                    $styleString = '';
//                                    $fontFamily && $styleString .= "font-family:{$fontFamily};";
//                                    $fontSize && $styleString .= "font-size:{$fontSize}px;";
//                                    $isBold && $styleString .= "font-weight:bold;";
//                                    $html .= sprintf('<span style="%s">%s</span>',
//                                        $styleString,
//                                        mb_convert_encoding($ele2->getText(), 'GBK', 'UTF-8')
//                                    );
//                                } elseif ($ele2 instanceof Image) {
//                                    $imageSrc = $pathInfo['dirname'] . DS . $pathInfo['filename'] . '_' . md5($ele2->getSource()) . '.' . $ele2->getImageExtension();
////                                    $imageSrc = 'images/' . md5($ele2->getSource()) . '.' . $ele2->getImageExtension();x
////                                    $imageData = $ele2->getImageStringData(true);
//                                    dump($ele2->getSource());
//                                    dump($ele2->getTarget());exit;
//                                    // $imageData = 'data:' . $ele2->getImageType() . ';base64,' . $imageData;
//                                    file_put_contents($imageSrc, base64_decode($imageData));
//                                    $attachment = ['url' => $imageSrc];
//                                    $result = \think\Hook::listen("upload_after", $attachment);
//                                    if($result){
//                                        dump($result);exit;
//                                    }
////                                    $imageFile = DS . 'public' . DS . pathinfo($imageSrc, PATHINFO_BASENAME);
//
//
//                                    $html .= '<img src="' . $imageSrc . '" style="width:100%;height:auto">';
//                                }
//                            }
//                        }
//                        $html .= '</p>';
//                    }
//                }
//                $content = mb_convert_encoding($html, 'UTF-8', 'GBK');


                $phpWord = IOFactory::load($filePath);
                $xmlWriter = IOFactory::createWriter($phpWord, "HTML");
                $tempHtml = $pathInfo['dirname'] . DS . $pathInfo['filename'] . '.html';
                $xmlWriter->save($tempHtml);
                $content = file_get_contents($tempHtml);
                @unlink($tempHtml);
                break;
            case 'txt':
                $content = file_get_contents($filePath);
                break;
            default:
                $this->error(__('Unknown data format'));
        }
        @unlink($filePath);
        $data = [
            'title'       => '未标题文档',
            'sub_title'   => '',
            'mark'        => '',
            'cover_image' => '',
            'content'     => $content,
            'read_count'  => 0,
            'status'      => 'hidden'
        ];
        $this->model->save($data);
        $this->success('', '', ['id' => $this->model->id]);
    }
}